/**
 * 基础工具函数
 */

/**
 * 判断当前是否处于全屏状态
 * @returns {Boolean} 是否全屏
 */
export function isFullscreen() {
  return !!(
    document.fullscreenElement ||
    document.mozFullScreenElement ||
    document.webkitFullscreenElement ||
    document.msFullscreenElement
  )
}

/**
 * 切换全屏状态
 * @param {HTMLElement} element 要全屏的元素，默认为document.documentElement
 */
export function toggleFullscreen(element = document.documentElement) {
  if (isFullscreen()) {
    // 退出全屏
    if (document.exitFullscreen) {
      document.exitFullscreen()
    } else if (document.mozCancelFullScreen) {
      document.mozCancelFullScreen()
    } else if (document.webkitExitFullscreen) {
      document.webkitExitFullscreen()
    } else if (document.msExitFullscreen) {
      document.msExitFullscreen()
    }
  } else {
    // 进入全屏
    if (element.requestFullscreen) {
      element.requestFullscreen()
    } else if (element.mozRequestFullScreen) {
      element.mozRequestFullScreen()
    } else if (element.webkitRequestFullscreen) {
      element.webkitRequestFullscreen()
    } else if (element.msRequestFullscreen) {
      element.msRequestFullscreen()
    }
  }
}

/**
 * 防抖函数
 * @param {Function} fn 要执行的函数
 * @param {Number} delay 延迟时间，单位毫秒
 * @returns {Function} 防抖后的函数
 */
export function debounce(fn, delay = 300) {
  let timer = null
  return function(...args) {
    if (timer) clearTimeout(timer)
    timer = setTimeout(() => {
      fn.apply(this, args)
    }, delay)
  }
}

/**
 * 节流函数
 * @param {Function} fn 要执行的函数
 * @param {Number} threshold 时间阈值，单位毫秒
 * @returns {Function} 节流后的函数
 */
export function throttle(fn, threshold = 300) {
  let last
  let timer
  return function(...args) {
    const now = Date.now()
    if (last && now < last + threshold) {
      clearTimeout(timer)
      timer = setTimeout(() => {
        last = now
        fn.apply(this, args)
      }, threshold)
    } else {
      last = now
      fn.apply(this, args)
    }
  }
}

/**
 * 格式化日期时间
 * @param {Date|String|Number} date 日期对象或时间戳
 * @param {String} format 格式化模板，例如 'YYYY-MM-DD HH:mm:ss'
 * @returns {String} 格式化后的日期字符串
 */
export function formatDate(date, format = 'YYYY-MM-DD HH:mm:ss') {
  if (!date) return ''
  
  // 转换为日期对象
  const dateObj = typeof date === 'object' ? date : new Date(date)
  
  const formatObj = {
    YYYY: dateObj.getFullYear(),
    MM: String(dateObj.getMonth() + 1).padStart(2, '0'),
    DD: String(dateObj.getDate()).padStart(2, '0'),
    HH: String(dateObj.getHours()).padStart(2, '0'),
    mm: String(dateObj.getMinutes()).padStart(2, '0'),
    ss: String(dateObj.getSeconds()).padStart(2, '0'),
    SSS: String(dateObj.getMilliseconds()).padStart(3, '0')
  }
  
  return format.replace(/(YYYY|MM|DD|HH|mm|ss|SSS)/g, (match) => formatObj[match])
}

/**
 * 复制文本到剪贴板
 * @param {String} text 要复制的文本
 * @returns {Promise} 复制结果的Promise
 */
export function copyToClipboard(text) {
  // 使用现代API
  if (navigator.clipboard && navigator.clipboard.writeText) {
    return navigator.clipboard.writeText(text)
  }
  
  // 兼容处理
  return new Promise((resolve, reject) => {
    const textarea = document.createElement('textarea')
    textarea.value = text
    textarea.style.position = 'fixed'
    textarea.style.opacity = '0'
    document.body.appendChild(textarea)
    textarea.select()
    
    try {
      const successful = document.execCommand('copy')
      document.body.removeChild(textarea)
      if (successful) {
        resolve(true)
      } else {
        reject(new Error('复制失败'))
      }
    } catch (err) {
      document.body.removeChild(textarea)
      reject(err)
    }
  })
}

/**
 * 获取浏览器信息
 * @returns {Object} 浏览器信息对象
 */
export function getBrowserInfo() {
  const ua = navigator.userAgent.toLowerCase()
  const match = 
    /(chrome)[ /]([\w.]+)/.exec(ua) ||
    /(firefox)[ /]([\w.]+)/.exec(ua) ||
    /(safari)[ /]([\w.]+)/.exec(ua) ||
    /(opera)[ /]([\w.]+)/.exec(ua) ||
    /(msie) ([\w.]+)/.exec(ua) ||
    /trident.*rv:([\w.]+)/.exec(ua) || []
  
  const result = {
    browser: match[1] || '',
    version: match[2] || '0',
    mobile: /mobile|android|iphone|ipad|ipod|blackberry|iemobile|opera mini/.test(ua)
  }
  
  // 特殊处理 Edge
  if (ua.indexOf('edg') > -1) {
    result.browser = 'edge'
    result.version = /edg[ /]([\w.]+)/.exec(ua)[1] || '0'
  }
  
  return result
}

/**
 * 生成UUID
 * @returns {String} UUID字符串
 */
export function generateUUID() {
  return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, (c) => {
    const r = (Math.random() * 16) | 0
    const v = c === 'x' ? r : (r & 0x3) | 0x8
    return v.toString(16)
  })
}

/**
 * 获取URL参数
 * @param {String} name 参数名
 * @param {String} url URL，默认为当前页面URL
 * @returns {String|null} 参数值
 */
export function getUrlParam(name, url = window.location.href) {
  const reg = new RegExp('(^|&|\\?)' + name + '=([^&]*)(&|$)')
  const match = url.match(reg)
  return match ? decodeURIComponent(match[2]) : null
}

/**
 * 数字千分位格式化
 * @param {Number} num 数字
 * @returns {String} 格式化后的字符串
 */
export function formatNumber(num) {
  if (isNaN(num)) return '0'
  return num.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ',')
}

/**
 * 金额格式化
 * @param {Number} amount 金额
 * @param {Number} decimals 小数位数
 * @param {String} decimalSeparator 小数点符号
 * @param {String} thousandsSeparator 千分位符号
 * @returns {String} 格式化后的金额字符串
 */
export function formatCurrency(amount, decimals = 2, decimalSeparator = '.', thousandsSeparator = ',') {
  if (isNaN(amount)) return '0'
  
  const fixed = Number(amount).toFixed(decimals)
  const [integer, decimal] = fixed.split('.')
  
  const formattedInteger = integer.replace(/\B(?=(\d{3})+(?!\d))/g, thousandsSeparator)
  
  return decimal ? formattedInteger + decimalSeparator + decimal : formattedInteger
} 